/* 
** (Copyright) sejishikong <sejishikong@263.net>
** Authors:    sejishikong <sejishikong@263.net>
**             Wei Lian <lianwei2003.student@sina.com> 
** Maintainer: Wei Lian
**    This program is free software; you can redistribute it and/or modify
**    it under the terms of the GNU General Public License Version 2 as
**    published by the Free Software Foundation;
**
**    This program is distributed in the hope that it will be useful,
**    but WITHOUT ANY WARRANTY; without even the implied warranty of
**    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
**    GNU General Public License for more details.
**
**    You should have received a copy of the GNU General Public License
**    along with this program; if not, write to the Free Software
**    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
**
*/
#include "header.h"
#include "channel.h"
#include "mainwindow.h"
#include "mylistitem.h"
#include "config.h"
#include "mystatusbar.h"
#include "mylabel.h"

Channel::Channel (QWidget * parent, const char *name, WFlags f):
QListView (parent, name, f),
mainwindow (static_cast < Sopcast * >(parent))
{
  fetchingchannel = FALSE;
  bufchannel = new QBuffer ();
  http = new QHttp (this);
  connect (http, SIGNAL (done (bool)), SLOT (httpdone (bool)));

  addColumn (tr ("Name"));
/*  addColumn (tr ("Status"));
  addColumn (tr ("Type"));
  addColumn (tr ("Kbps"));
  addColumn (tr ("Users"));
  addColumn (tr ("Vists"));
  addColumn (tr ("QualityS"));
  addColumn (tr ("QualityC"));
  addColumn (tr ("StarFrom"));
  addColumn (tr ("URL"));
  addColumn (tr ("Description"));*/
  setRootIsDecorated (TRUE);

  connect (this, SIGNAL (doubleClicked (QListViewItem *)), mainwindow,
	   SLOT (onlistitemclicked (QListViewItem *)));
  connect (this, SIGNAL (returnPressed (QListViewItem *)), mainwindow,
	   SLOT (onlistitemclicked (QListViewItem *)));
  connect (this,
	   SIGNAL (rightButtonClicked (QListViewItem *, const QPoint &, int)),
	   this,
	   SLOT (onrightbuttonclicked
		 (QListViewItem *, const QPoint &, int)));
  connect (this, SIGNAL (onItem (QListViewItem *)), this,
	   SLOT (onmousemoved (QListViewItem *)));

  //popup
  popup = new MyLabel (this);

}

Channel::~Channel ()
{
  delete bufchannel;
}

void
Channel::fetchchannel ()
{
  if (fetchingchannel == FALSE)
    {
      fetchingchannel = TRUE;
      mainwindow->buttonchannel->setOn (TRUE);
      if (!bufchannel->open (IO_ReadWrite))
	{
	  printf ("cannot create the buffer\n");
	  return;
	}

      QString str = vboxconfig->editchannelurl->text ();
      http->setHost (str.section ("/", 2, 2));	//"www.sopcast.org");
      http->get ("/" + str.section ("/", 3), bufchannel);	//"/channel/index.php", bufchannel);
    }
  else
    {
      if (!mainwindow->buttonchannel->isOn ())
	mainwindow->buttonchannel->setOn (TRUE);
    }
}

void
Channel::httpdone (bool error)
{
  ///reset button state
  if (mainwindow->buttonchannel->isOn ())
    mainwindow->buttonchannel->setOn (FALSE);
  fetchingchannel = FALSE;

  if (error)
    {
      mainwindow->statusbar->message ("load page error", 3000);
      fprintf (stderr, "load page error!\n");
      bufchannel->close ();
      return;
    }

  ///disable sorting
  if (!vboxconfig->radiochannelsort->isOn ())
    setSortColumn (-1);
  else
    setSortColumn (0);
  ///

  bufchannel->reset ();
  QDomDocument doc ("mydocument");
  doc.setContent (bufchannel);
  bufchannel->close ();

  QDomElement root = doc.documentElement ();
  QDomNode node = root.firstChild ();

  QDomNode channelnode, namenode;
  MyListItem *groupitem = 0, *item = 0;

  mainwindow->updateopenstate ();
  clear ();
  int MaxUser = 1;
  ///group
  while (!node.isNull ())
    {
      if (node.isElement () && node.nodeName () == "group")
	{
	  groupitem = new MyListItem (this, groupitem);
	  groupitem->setText (0, node.firstChild ().toText ().nodeValue ());
	  ///channel
	  int count = 0;
	  bool found = false;
	  channelnode = node.toElement ().firstChild ();
	  while (!channelnode.isNull ())
	    {
	      if (channelnode.isElement ()
		  && channelnode.nodeName () == "channel")
		{
		  ///element
		  item = new MyListItem (groupitem, item);

		  namenode = channelnode.toElement ().firstChild ();
		  while (!namenode.isNull ())
		    {
		      if (namenode.nodeName () == "name")
			item->setText (NAME_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "status")
			item->setText (STATUS_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "stream_type")
			item->setText (STREAM_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "kbps")
			item->setText (KBPS_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "user_count")
			item->setText (USER_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "visit_count")
			item->setText (VISIT_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "qs")
			item->setText (QS_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "qc")
			item->setText (QC_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "start_from")
			item->setText (START_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      else if (namenode.nodeName () == "sop_address")
			item->setText (URL_COLUMN,
				       namenode.firstChild ().toElement ().
				       firstChild ().toText ().nodeValue ());
		      else if (namenode.nodeName () == "description")
			item->setText (DESCRIPTION_COLUMN,
				       namenode.firstChild ().toText ().
				       nodeValue ());
		      namenode = namenode.nextSibling ();
		    }

		  ///filtering out channel
		  if (channelnode.toElement ().attribute ("type").
		      toInt () == 1)
		    {
		      found = true;
		      item->setEnabled (FALSE);
		      item->setVisible (FALSE);
		    }
		  ///disable null channel
		  else if (item->text (URL_COLUMN) == "null")
		    {
		      item->setEnabled (FALSE);
		      if (!vboxconfig->radionullchannel->isOn ())
			item->setVisible (FALSE);
		    }
		  else
		    {
		      count++;

		      MaxUser =
			item->text (USER_COLUMN).toInt () >
			MaxUser ? item->text (USER_COLUMN).toInt () : MaxUser;
//                          item->setPixmap (0, folder_open_xpm);
		    }

		}
	      channelnode = channelnode.nextSibling ();
	    }

	  ///hide empty group
	  if (count == 0)
	    {
	      if (!vboxconfig->radionullchannel->isOn () || found)
		groupitem->setVisible (FALSE);
	    }
	}
      node = node.nextSibling ();
    }

  ///set open and set color
  QListViewItem *group = firstChild ();
  int count = 0;
  while (group)
    {
      ///set open
      if (mainwindow->stateopen[count++] == 1)
	group->setOpen (TRUE);
      ///set color
      QListViewItem *child = group->firstChild ();
      while (child)
	{
	  if (child->isEnabled ())
	    {
	      int level =
		int (child->text (USER_COLUMN).toInt () * (255. / MaxUser));
	      level = level < 0 ? 0 : level;
	      level = level > 255 ? 255 : level;
	      static_cast < MyListItem * >(child)->fcolor.setHsv (255 - level,
								  255, 125);
	    }
	  child = child->nextSibling ();
	}
      group = group->nextSibling ();
    }

}

void
Channel::onrightbuttonclicked (QListViewItem * item, const QPoint & pos, int)
{
  if (item)
    if (item->depth () == 1)
      {
//  popup->move (mapToGlobal (channel->itemRect (i).topLeft ()));//
	popup->move (pos);
	popup->
	  setText ("<table border=0 cellspacing=0 cellpadding=0><tr><td>" +
		   item->text (NAME_COLUMN) + "</td></tr></table><hr>"
		   "<table border=0 cellspacing=0 cellpadding=0>"
		   "<tr><td>Users: " + item->text (USER_COLUMN) +
		   "</td><td>Visitors: " + item->text (VISIT_COLUMN) +
		   "</td></tr>" "<tr><td>QualityC: " +
		   item->text (QC_COLUMN) + "</td><td>QualityS: " +
		   item->text (6) + "</td></tr>" "<tr><td>MediaType: " +
		   item->text (STREAM_COLUMN) + "</td><td>KBps: " +
		   item->text (KBPS_COLUMN) +
		   "</td></tr>" "<tr><td>StartFrom: " +
		   item->text (START_COLUMN) + "</td></tr></table><br>" +
		   item->text (DESCRIPTION_COLUMN));
	popup->adjustSize ();
	popup->show ();
      }
}

void
Channel::onmousemoved (QListViewItem *)
{
  popup->hide ();
}


void
Channel::mouseMoveEvent (QMouseEvent * e)
{
  QPoint p (e->pos ());
  QRect pr (rect ());
  pr.setWidth (pr.width () - verticalScrollBar ()->width ());
  pr.setHeight (pr.height () - horizontalScrollBar ()->height ());

  if (!pr.contains (p))
    {
      popup->hide ();
    }
}
